package com.viethp.mt.activities;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.ArrayWheelAdapter;

import com.viethp.mt.common.CommonHelper;
import com.viethp.mt.common.GlobalVariables;
import com.viethp.mt.common.HttpFileUploader;
import com.viethp.mt.common.MyLocationListener;
//import com.viethp.mt.objects.AddPostResponse;
//import com.viethp.mt.objects.CancelActivityResponse;
import com.viethp.mt.objects.DeletePostResponse;
import com.viethp.mt.objects.EditPostResponse;
import com.viethp.mt.objects.Position;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnticipateOvershootInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class AGroupHaveDetails extends Activity implements OnClickListener {

	private static final int REQUEST_GALLERY = 1336;
	private static final int REQUEST_CAMERA = 1337;
	private static final int REQUEST_TITLE = 1111;

	private static final String ITEM_ID = "item_id";
	private static final String ACTIVITY_ID = "activity_id";
	private static final String ITEM_TITLE = "title";
	private static final String ITEM_DESCRIPTION = "description";
	private static final String ITEM_EXP = "expired";
	private static final String ITEM_PRICE = "price";
	private static final String TOTAL_BIDDER = "total_bidder";
	private static final String MAX_BUDGET = "max_budget";
	// private static final String YOUR_PRICE = "your_price";
	private static final String ITEM_IMG_LINK = "imgLink";
	private static final String CATEGORY_ID = "category_id";
	private static final String ITEM_STATUS = "status";

	private Bitmap selectedAvatar;
//	private Bitmap bitmap;
	private int status;
	private boolean is_update;
	String imageSrc;

	private Button btn_applicant, btn_post_edit, btn_post_del, btn_back,
			btn_activity_count;
	private String item_id, title, desc, exp, price, imgLink, total_bidder,
			max_budget, activity_id, category_id, activity_status;
//	private String  your;
	private TextView tv_post_title, tv_post_exp, tv_post_price, tv_post_desc,
			tv_post_total_bidder, tv_post_max_budget;

	private String[] exp_hours_list_array = new String[] { "0", "1", "2", "3",
			"4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15",
			"16", "17", "18", "19", "20", "21", "22", "23" };
	private String[] exp_days_list_array = new String[] { "0", "1", "2", "3",
			"4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15",
			"16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26",
			"27", "28", "29", "30"};
	private String[] exp_mons_list_array = new String[] { "0", "1", "2", "3" };

	private ProgressDialog progressDialog;
	private ImageView img;
	private EditText edt_title;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.a_have_details);

		Intent extras = getIntent();
		item_id = extras.getStringExtra(ITEM_ID);
		activity_id = extras.getStringExtra(ACTIVITY_ID);
		title = extras.getStringExtra(ITEM_TITLE);
		desc = extras.getStringExtra(ITEM_DESCRIPTION);
		exp = extras.getStringExtra(ITEM_EXP);
		price = extras.getStringExtra(ITEM_PRICE);
		imgLink = extras.getStringExtra(ITEM_IMG_LINK);
		total_bidder = extras.getStringExtra(TOTAL_BIDDER);
		max_budget = extras.getStringExtra(MAX_BUDGET);
		category_id = extras.getStringExtra(CATEGORY_ID);
		activity_status = extras.getStringExtra(ITEM_STATUS);
		// your = extras.getStringExtra(YOUR_PRICE);
		Log.d("getextra", "" + category_id);

		initComponents();
		setOnClickListener();
		setInfo();
		setPosition();
		check();
	}

	public void check() {
		if (Integer.parseInt(exp) == -1) {
			btn_activity_count.setVisibility(View.INVISIBLE);
		}
		if(Integer.parseInt(activity_status) == 3){
			btn_activity_count.setVisibility(View.INVISIBLE);
			btn_post_edit.setVisibility(View.INVISIBLE);
		}
	}

	public void setInfo() {
		tv_post_title.setText(title);
		if (Integer.parseInt(exp) == -1) {
			tv_post_exp.setText("Expired");
		} else
			tv_post_exp.setText(CommonHelper.timeLeft(Long.parseLong(exp)));
		tv_post_price.setText("$"+price);
		tv_post_desc.setText(desc);
		tv_post_total_bidder.setText(total_bidder);
		tv_post_max_budget.setText("$"+max_budget);
		// tv_post_your.setText(your);
		Bitmap bm = CommonHelper.getImageBitmap(imgLink);
		img.setImageBitmap(bm);
		btn_activity_count.setText(total_bidder);
		if (Integer.valueOf(total_bidder) == 0)
			btn_activity_count.setVisibility(View.INVISIBLE);
	}

	public void initComponents() {
		tv_post_title = (TextView) findViewById(R.id.tv_post_title);
		tv_post_exp = (TextView) findViewById(R.id.tv_post_exp);
		tv_post_price = (TextView) findViewById(R.id.tv_post_price);
		tv_post_desc = (TextView) findViewById(R.id.tv_post_desc);
		tv_post_total_bidder = (TextView) findViewById(R.id.tv_post_total_bidder);
		tv_post_max_budget = (TextView) findViewById(R.id.tv_post_max_budget);

		btn_applicant = (Button) findViewById(R.id.btn_activity_count);
		btn_back = (Button) findViewById(R.id.btn_back);
		btn_post_edit = (Button) findViewById(R.id.btn_post_edit);
		btn_post_del = (Button) findViewById(R.id.btn_post_del);
		btn_activity_count = (Button) findViewById(R.id.btn_activity_count);

		img = (ImageView) findViewById(R.id.img_post_image);
		status = 0;
		is_update = false;

		progressDialog = new ProgressDialog(AGroupHaveDetails.this);
		progressDialog.setCancelable(false);
	}

	public void setOnClickListener() {
		btn_applicant.setOnClickListener(this);
		btn_back.setOnClickListener(this);
		btn_post_edit.setOnClickListener(this);
		btn_post_del.setOnClickListener(this);
		btn_activity_count.setOnClickListener(this);

		img.setOnClickListener(this);
		tv_post_title.setOnClickListener(this);
		tv_post_price.setOnClickListener(this);
		tv_post_exp.setOnClickListener(this);
		tv_post_desc.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_activity_count:
			Intent i = new Intent(this, AApplicantList.class);
			i.putExtra(ITEM_ID, item_id);
			startActivity(i);
			break;
		case R.id.btn_back:
			this.finish();
			break;
		case R.id.btn_post_edit:
			if (is_update) {
				if (status == 1) {
					doUpload();
				} else {
					imageSrc = imgLink;
					doEditPost();
				}
			}
			break;
		case R.id.btn_post_del:
			showDeleteConfirm().show();
			break;
		case R.id.img_post_image:
			showDialogAddImage().show();
			break;
		case R.id.tv_post_title:
			DialogTitle();
			break;
		case R.id.tv_post_price:
			DialogPrice();
			break;
		case R.id.tv_post_exp:
			DialogEXP();
			break;
		case R.id.tv_post_desc:
			DialogDesc();
			break;
		default:
			break;
		}

	}

	private WheelView initWheel(int id, String[] values, View view) {
		WheelView wheel = (WheelView) view.findViewById(id);
		ArrayWheelAdapter<String> adapter = new ArrayWheelAdapter<String>(this,
				values);
		adapter.setTextSize(20);
		wheel.setViewAdapter(adapter);
		wheel.setCurrentItem(1);
		wheel.setCyclic(true);
		wheel.setInterpolator(new AnticipateOvershootInterpolator());

		return wheel;
	}

	protected Dialog showDialogAddImage() {

		final CharSequence[] items = { "Take a picture", "Pick from gallery" };
		return new android.app.AlertDialog.Builder(this)
				.setTitle(getString(R.string.post_add_image))
				.setItems(items, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						if (item == 1) {
							CommonHelper.callGallery(AGroupHaveDetails.this,
									REQUEST_GALLERY);

						} else if (item == 0) {
							String oXY = String.valueOf(CommonHelper.dptopx(
									(float) 120, AGroupHaveDetails.this));
							Intent cameraIntent = new Intent(
									android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
							cameraIntent.putExtra("outputX", oXY);
							cameraIntent.putExtra("outputY", oXY);
							cameraIntent.putExtra("aspectX", 0);
							cameraIntent.putExtra("aspectY", 0);
							cameraIntent.putExtra("scale", true);
							cameraIntent.putExtra("return-data", true);
							try {

								startActivityForResult(cameraIntent,
										REQUEST_CAMERA);
							} catch (ActivityNotFoundException e) {
								// Do nothing for now
							}
						}
					}
				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(
									android.content.DialogInterface dialog,
									int whichButton) {

							}
						}).create();
	}

	public void DialogTitle() {

		LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View view = layoutInflater.inflate(R.layout.dialog_post_input,
				null);
		edt_title = (EditText) view.findViewById(R.id.edt_post_input);
		InputFilter[] FilterArray = new InputFilter[1];
		FilterArray[0] = new InputFilter.LengthFilter(20);
		edt_title.setFilters(FilterArray);

		final Dialog dia = new Dialog(this);
		dia.setContentView(view);
		dia.setTitle("Enter Title");
		dia.getWindow().setLayout(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);
		dia.setCancelable(false);
		dia.show();

		final Button btn_change = (Button) view.findViewById(R.id.btn_change);
		if (String.valueOf(edt_title.getText()).equals(""))
			btn_change.setEnabled(false);
		edt_title.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (String.valueOf(edt_title.getText()).trim().equals("")
						|| String.valueOf(edt_title.getText()).trim().length() < 6)
					btn_change.setEnabled(false);
				else
					btn_change.setEnabled(true);
			}
		});

		btn_change.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				title = edt_title.getText().toString().trim();
				tv_post_title.setText(title);
				is_update = true;
				dia.dismiss();
			}
		});
		Button btn_cancel = (Button) view.findViewById(R.id.btn_cancel);
		btn_cancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dia.dismiss();

			}
		});
	}

	public void DialogPrice() {

		LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View view = layoutInflater.inflate(R.layout.dialog_post_input,
				null);
		edt_title = (EditText) view.findViewById(R.id.edt_post_input);
		edt_title.setInputType(InputType.TYPE_CLASS_NUMBER);

		final Dialog dia = new Dialog(this);
		dia.setContentView(view);
		dia.setTitle("Enter Price");
		dia.getWindow().setLayout(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);
		dia.setCancelable(false);
		dia.show();

		final Button btn_change = (Button) view.findViewById(R.id.btn_change);
		if (String.valueOf(edt_title.getText()).equals(""))
			btn_change.setEnabled(false);
		edt_title.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (String.valueOf(edt_title.getText()).trim().equals(""))
					btn_change.setEnabled(false);
				else
					btn_change.setEnabled(true);
			}
		});

		btn_change.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				price = edt_title.getText().toString().trim();
				tv_post_price.setText(price);
				is_update = true;
				dia.dismiss();
			}
		});
		Button btn_cancel = (Button) view.findViewById(R.id.btn_cancel);
		btn_cancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dia.dismiss();

			}
		});
	}

	public void DialogEXP() {
		LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View view = layoutInflater.inflate(R.layout.dialog_exp, null);
		final WheelView mon = initWheel(R.id.exp_mons, exp_mons_list_array,
				view);
		final WheelView day = initWheel(R.id.exp_days, exp_days_list_array,
				view);
		final WheelView hour = initWheel(R.id.exp_hours, exp_hours_list_array,
				view);

		final Dialog dia = new Dialog(this);
		dia.setContentView(view);
		dia.setTitle("choose EXP");
		dia.getWindow().setLayout(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);
		dia.setCancelable(false);
		dia.show();

		final Button btn_change = (Button) view.findViewById(R.id.btn_change);
		btn_change.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				int mons = mon.getCurrentItem();
				int days = day.getCurrentItem();
				int hours = hour.getCurrentItem();
				long expired = CommonHelper.toSecond(mons, days, hours);
				exp = String.valueOf(expired);
				String exp_left = CommonHelper.timeLeft((int) expired);
				tv_post_exp.setText(String.valueOf(exp_left));
				is_update = true;
				dia.dismiss();
			}
		});
		Button btn_cancel = (Button) view.findViewById(R.id.btn_cancel);
		btn_cancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dia.dismiss();

			}
		});
	}

	public void DialogDesc() {
		LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View view = layoutInflater.inflate(R.layout.dialog_post_input,
				null);
		edt_title = (EditText) view.findViewById(R.id.edt_post_input);

		final Dialog dia = new Dialog(this);
		dia.setContentView(view);
		dia.setTitle("Enter Description");
		dia.getWindow().setLayout(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);
		dia.setCancelable(false);
		dia.show();

		final Button btn_change = (Button) view.findViewById(R.id.btn_change);
		if (String.valueOf(edt_title.getText()).equals(""))
			btn_change.setEnabled(false);
		edt_title.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (String.valueOf(edt_title.getText()).trim().equals(""))
					btn_change.setEnabled(false);
				else
					btn_change.setEnabled(true);
			}
		});

		btn_change.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				desc = edt_title.getText().toString().trim();
				tv_post_desc.setText(desc);
				is_update = true;
				dia.dismiss();
			}
		});
		Button btn_cancel = (Button) view.findViewById(R.id.btn_cancel);
		btn_cancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dia.dismiss();

			}
		});
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == RESULT_OK) {

			if (requestCode == REQUEST_GALLERY) {
				Uri currImageURI = data.getData();
				try {
					InputStream in = getContentResolver().openInputStream(
							currImageURI);

					selectedAvatar = BitmapFactory.decodeStream(in);
					img.setImageBitmap(CommonHelper
							.getRoundedCornerBitmapGallery(selectedAvatar));
					is_update = true;
					status = 1;

				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
			if (requestCode == REQUEST_CAMERA) {
				try {

					selectedAvatar = (Bitmap) data.getExtras().get("data");
					img.setImageBitmap(CommonHelper.getRoundedCornerBitmap(
							selectedAvatar, AGroupHaveDetails.this));
					is_update = true;
					status = 1;

				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
			if (requestCode == REQUEST_TITLE) {
				String d = data.getStringExtra("TITLE");
				tv_post_title.setText(d);
			}
		}
	}

	private int UpImage(Bitmap bm) {
		String imgName = String.valueOf(CommonHelper.getCurrentDate()) + ".PNG";
		try {
			ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
			if ((bm.getHeight() < 367) && bm.getWidth() < 320)
				bm.compress(CompressFormat.PNG, 75, bos1);
			else {
				int hs = 367;
				int ws = 320;
				if (bm.getWidth() < ws)
					ws = bm.getWidth();
				if (bm.getHeight() < hs)
					hs = bm.getHeight();
				CommonHelper.getResizedBitmap(bm, ws, hs).compress(
						CompressFormat.PNG, 75, bos1);
			}

			byte[] data1 = bos1.toByteArray();
			HttpFileUploader t1 = new HttpFileUploader(
					GlobalVariables.UPLOAD_URL, imgName, data1, "");
			if (t1.doUpload().toString().equals("")) {
				imageSrc = GlobalVariables.UPLOAD_URLIMAGE + imgName;
				Log.d("IMG", "1");
				return GlobalVariables.ReOK;
			}
		} catch (Exception e) {
			Log.d("IMG", "2");
			return GlobalVariables.ReFail;
		}
		return GlobalVariables.ReOK;
	}

	private void doUpload() {
		if (CommonHelper.isNetworkAvailable(this)) {
			startCallServiceUpload();
		} else
			CommonHelper.showWarning(AGroupHaveDetails.this,
					getString(R.string.netstate));
	}

	public void startCallServiceUpload() {
		progressDialog.setMessage(getString(R.string.pleasewait));
		progressDialog.show();

		new Thread(new Runnable() {

			@Override
			public void run() {
				Message message = new Message();
				message.what = UpImage(selectedAvatar);
				handlerUpload.sendMessage(message);

			}
		}).start();
	}

	private Handler handlerUpload = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			progressDialog.dismiss();

			if (msg.what == GlobalVariables.ReOK) {
				doEditPost();
			} else {
				CommonHelper.showWarning(AGroupHaveDetails.this,
						getString(R.string.disconnect));
			}

		};
	};

	public void startCallServiceEditPost() {
		progressDialog.setMessage(getString(R.string.pleasewait));
		progressDialog.show();

		new Thread(new Runnable() {

			@Override
			public void run() {
				Message message = new Message();
				message.obj = callServiceEditPost();
				handlerEditPost.sendMessage(message);

			}
		}).start();
	}

	private Handler handlerEditPost = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			progressDialog.dismiss();

			if (msg.obj != null) {
				EditPostResponse response = (EditPostResponse) msg.obj;
				if (response.getErrorCode() != null) {
					CommonHelper.showWarning(AGroupHaveDetails.this, response
							.getErrorCode().getErrMsg());
				} else {
					CommonHelper.showWarning(AGroupHaveDetails.this,
							"Update Successful!");
					status = 0;
					// checkEXP();

				}

			} else {
				CommonHelper.showWarning(AGroupHaveDetails.this,
						getString(R.string.disconnect));
			}

		};
	};

	private void doEditPost() {
		if (CommonHelper.isNetworkAvailable(this)) {
			startCallServiceEditPost();
		} else
			CommonHelper.showWarning(AGroupHaveDetails.this,
					getString(R.string.netstate));
	}

	private EditPostResponse callServiceEditPost() {

		SoapObject userRequest = new SoapObject(GlobalVariables.WS_NAMESPACE,
				GlobalVariables.WS_METHOD_EDIT_ACTIVITY);
		userRequest.addProperty("user_id",
				CommonHelper.getUserLogin(AGroupHaveDetails.this).getId());
		userRequest.addProperty("title", title);
		userRequest.addProperty("description", desc);
		userRequest.addProperty("price", price);
		userRequest.addProperty("expired", exp);
		userRequest.addProperty("longitude", CommonHelper.getPosition(this)
				.getLon());
		Log.d("lon", CommonHelper.getPosition(this).getLon());
		userRequest.addProperty("latitude", CommonHelper.getPosition(this)
				.getLat());
		Log.d("lat", CommonHelper.getPosition(this).getLat());
		userRequest.addProperty("imgLink", imageSrc);
		userRequest.addProperty("item_id", item_id);
		userRequest.addProperty("activity_id", activity_id);
		userRequest.addProperty("category_id", category_id);

		SoapObject request = new SoapObject(GlobalVariables.WS_NAMESPACE,
				GlobalVariables.WS_METHOD_EDIT_ACTIVITY);
		request.addProperty(GlobalVariables.WS_METHOD_EDIT_ACTIVITY,
				userRequest);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(request);

		HttpTransportSE androidHttpTransport = new HttpTransportSE(
				GlobalVariables.WS_ENDPOINT,
				GlobalVariables.WS_CONNECTTION_TIME_OUT);
		SoapObject results = null;
		try {
			androidHttpTransport.call(GlobalVariables.WS_NAMESPACE
					+ GlobalVariables.WS_METHOD_EDIT_ACTIVITY, envelope);
		} catch (Exception e) {
			try {
				androidHttpTransport.call(GlobalVariables.WS_NAMESPACE
						+ GlobalVariables.WS_METHOD_EDIT_ACTIVITY, envelope);
			} catch (Exception e1) {
				e1.printStackTrace();
				return null;

			}
		}
		try {
			results = (SoapObject) envelope.getResponse();
		} catch (SoapFault ex3) {
			ex3.printStackTrace();
			return null;
		}

		return new EditPostResponse(results);

	}

	public void setPosition() {
		LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Location loc = mlocManager
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		LocationListener mlocListener = new MyLocationListener(
				AGroupHaveDetails.this);

		mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
				mlocListener);
		if (loc != null) {
			Position pos = new Position();
			pos.setLon(String.valueOf(loc.getLongitude()));
			pos.setLat(String.valueOf(loc.getLatitude()));
			CommonHelper.setPosition(pos, this);
			CommonHelper.showToast(this, ""
					+ CommonHelper.getPosition(this).getLon() + " "
					+ CommonHelper.getPosition(this).getLat());
		} else {
			Position pos = new Position();
			if (CommonHelper.getPosition(this).getLon().equals("")
					|| CommonHelper.getPosition(this).getLat().equals("")) {
				pos.setLon(String.valueOf(GlobalVariables.lon));
				pos.setLat(String.valueOf(GlobalVariables.lat));
				CommonHelper.setPosition(pos, this);
			}

			CommonHelper.showToast(this, ""
					+ CommonHelper.getPosition(this).getLon() + " "
					+ CommonHelper.getPosition(this).getLat());
		}
	}

	// delete item
	protected Dialog showDeleteConfirm() {
		return new android.app.AlertDialog.Builder(this)
				.setMessage(getString(R.string.delete_confirm))
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								doDelete();
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(android.content.DialogInterface dialog,
							int whichButton) {
					}
				}).create();
	}

	public void doDelete() {
		if (CommonHelper.isNetworkAvailable(this)) {
			startCallServiceDelete();
		} else
			CommonHelper.showWarning(AGroupHaveDetails.this,
					getString(R.string.netstate));
	}

	public void startCallServiceDelete() {
		progressDialog.setMessage(getString(R.string.pleasewait));
		progressDialog.show();

		new Thread(new Runnable() {

			@Override
			public void run() {
				Message message = new Message();
				message.obj = callServiceDelete();
				handlerDelete.sendMessage(message);

			}
		}).start();
	}

	private DeletePostResponse callServiceDelete() {

		SoapObject userRequest = new SoapObject(GlobalVariables.WS_NAMESPACE,
				GlobalVariables.WS_METHOD_DELETE_ACTIVITY);
		// userRequest.addProperty("user_id",
		// CommonHelper.getUserLogin(AGroupWantDetails.this).getId());
		// userRequest.addProperty("item_id", item_id);
		userRequest.addProperty("item_id", item_id);

		SoapObject request = new SoapObject(GlobalVariables.WS_NAMESPACE,
				GlobalVariables.WS_METHOD_DELETE_ACTIVITY);
		request.addProperty(GlobalVariables.WS_METHOD_DELETE_ACTIVITY,
				userRequest);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(request);

		HttpTransportSE androidHttpTransport = new HttpTransportSE(
				GlobalVariables.WS_ENDPOINT,
				GlobalVariables.WS_CONNECTTION_TIME_OUT);
		SoapObject results = null;
		try {
			androidHttpTransport.call(GlobalVariables.WS_NAMESPACE
					+ GlobalVariables.WS_METHOD_DELETE_ACTIVITY, envelope);
		} catch (Exception e) {
			try {
				androidHttpTransport.call(GlobalVariables.WS_NAMESPACE
						+ GlobalVariables.WS_METHOD_DELETE_ACTIVITY, envelope);
			} catch (Exception e1) {
				e1.printStackTrace();
				return null;

			}
		}
		try {
			results = (SoapObject) envelope.getResponse();
		} catch (SoapFault ex3) {
			ex3.printStackTrace();
			return null;
		}

		return new DeletePostResponse(results);

	}

	private Handler handlerDelete = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			progressDialog.dismiss();

			if (msg.obj != null) {
				DeletePostResponse response = (DeletePostResponse) msg.obj;
				if (response.getErrorCode() != null) {
					CommonHelper.showWarning(AGroupHaveDetails.this, response
							.getErrorCode().getErrMsg());
				} else {
					//
					CommonHelper.showToast(AGroupHaveDetails.this,
							"Delete successful");

					// AGroupHaveDetails.this.finish();
					finishForResult();
				}

			} else {
				CommonHelper.showWarning(AGroupHaveDetails.this,
						getString(R.string.disconnect));
			}

		};
	};

	public void finishForResult() {
		Intent intent = getIntent();
		intent.putExtra("delete_status", "delete");
		setResult(RESULT_OK, intent);
		this.finish();
	}
}
